home *** CD-ROM | disk | FTP | other *** search
- u
-
-
- Alternative Programming Languages: C
- Part 1 By Paul Davis
-
-
- In the first article of this series we
- explored some of the capabilities of
- the Forth language. Forth has many
- unusual characteristics that make it
- well suited to programming on the
- Commodore, but it's a language that
- polarises opinion. Some people love
- it, some hate it, & some just can't
- seem to wrap their head around it. So
- this time we're going to look at a
- more mainstream language, C.
-
- C is a compiled language. It's not
- like BASIC or Forth where there's an
- interpreter you can type commands into
- & experiment with. Program code is
- entered into text files which are then
- run through a compiler to translate
- the source code into an executable
- program. This makes programming in C
- a bit more involved than you may be
- used to. Nevertheless, C is a very
- powerful & flexible language & is
- well worth adding to your programming
- repertoire.
-
- Although there are several
- implementations of C that run on the
- Commodore, the lack of memory & poor
- disk drive performance makes writing
- programs a laborious process. With
- that in mind, it provides a good
- opportunity to introduce the concept
- of cross-development. That is, using a
- modern computer to edit & compile
- our programs into a form that can be
- run either in an emulator or on a real
- Commodore machine.
-
- As was the case with the Forth
- article, this is not a complete
- tutorial. It's merely an intro to
- some of the features & programming
- style of the language to give you an
- idea of how it can be used. I'm
- going to follow a similar format as
- before & present some example programs
- with a brief commentary on how they
- work.
-
- Getting started
- We're going to be using a freeware C
- compiler called cc65 which is
- available in executable form for
- Windows, & as source code that can be
- compiled for OS X & Linux. The cc65
- website can be found at:
-
- http://www.cc65.org/
-
- We will also be using the VICE
- emulator to test our programs. If you
- don't already have this, it can be
- downloaded from:
-
- http://www.viceteam.org/
-
- The first step is to download &
- install cc65. Point your browser or
- favourite FTP client at the download
- area:
-
- ftp://ftp.musoftware.de/pub/uz/cc65/
-
- then follow the relevant instructions
- for your OS below.
-
- Windows XP & Vista
- Download the files called
- cc65-win32-2.12.0-1.zip &
- cc65-c64-2.12.0-1.zip. Next, create a
- directory where you want to install
- the compiler. This can be anywhere you
- like, although I would recommend
- avoiding the 'Program Files' directory
- (especially on Vista) or directories
- with spaces in their name. This
- article will assume the directory is
- C:\cc65. To install the program,
- extract the zip files you downloaded
- into the cc65 directory you have just
- created.
-
- Before we can use the compiler we need
- to set up our programming environment
- at the command prompt. Open a command
- prompt window (hold down the Windows
- key, press R then type 'cmd' & press
- Enter) & type the following
- commands:
-
- path %path%;c:\cc65\bin
- set CC65_INC=c:\cc65\include
- set CC65_LIB=c:\cc65\lib
-
- These instructions tell the command
- shell where to find the cc65 programs
- and tell cc65 where to find various
- files that are needed to compile a
- program.
-
- You will need to enter these commands
- each time you open a new command
- prompt window. If you want the
- settings to be permanent, here's how
- to do it. Press Windows + Break (or
- right-click on 'My Computer' & choose
- 'Properties') to bring up the System
- Properties dialog. On Vista select
- 'Advanced system settings' from the
- task panel on the left & confirm the
- UAC dialog. In the System Properties
- dialog click on the 'Advanced' tab,
- then on the 'Environment Variables'
- button. In the bottom panel for system
- variables click on 'New' then enter
-
- 'CC65_INC' for the name &
-
- 'c:\cc65\include' for the value
-
- & click 'OK'. Do the same for the
-
- 'CC65_LIB'
-
- variable with the value 'c:\cc65\lib'
-
- Next, scroll down the list to find the
- entry for 'Path' & double click it.
- Click on the value field & move the
- cursor to the end of the value then
- add ';c:\cc65\bin' to the end & click
- 'OK'. Click on the'OK' button of the
- Environment Variable & System
- Properties dialogs to complete the
- settings.
-
- Finally, we need to create a directory
- within the cc65 directory to store the
- files we will create during this
- tutorial.
-
- cd c:\cc65
- mkdir tut
- cd tut
-
- OS X & Linux
- To keep these instructions as short as
- possible I'm going to describe the
- procedure for OS X & assume Linux
- users will know how to deal with any
- differences.
-
- First, to compile cc65 we need to
- install the Xcode developer tools.
- Insert the OS X installation DVD that
- was shipped with your Mac & follow the
- links to install Xcode.
-
- Next, download the file called
- cc65-sources-2.12.0.tar.bz2 from the
- cc65 web site. You will not need to
- download any of the other files.
- Assuming the file has been saved to
- your 'Downloads' directory, open a new
- Finder window & navigate to that
- directory. Double-click on the
- cc65-sources file & the Archive
- Utility will extract it, creating a
- directory called 'cc65-2.12.0' in the
- Downloads directory.
-
- Now we need to work at a command line,
- so navigate to Applications then
- Utilities & double-click the Terminal
- program.
-
- Enter this command to change the
- current directory to the cc65
- directory in Downloads:
-
- cd /Downloads/cc65-2.12.0
-
- Now type this command to build the
- cc65 program suite:
-
- make -f make/gcc.mak
-
- This will take a minute or two to run.
- When the command prompt returns enter
- these lines:
-
- sudo mkdir /usr/local
- sudo make -f make/gcc.mak install
-
- You will probably need to enter the
- administrator password to run those
- commands. They will install cc65 into
- /usr/local/lib/cc65 & the
- executables into /usr/local/bin.
-
- At the end of the installation, there
- will be a message listing two
- variables that need to be set up. We
- will do this in a minute, but first we
- need to create a work directory to
- store the files that will be created
- during this tutorial. Enter these
- lines:
-
- cd /Documents
- mkdir cc65
- cd cc65
-
- To make setting up the environment
- variables a bit easier we will create
- a script to do it for us. Enter this
- command:
-
- xed -xc init.sh
-
- The Xcode editor will start up &
- show a blank document. Enter the
- following lines
- into the file:
-
- export CC65_INC=/usr/local/lib/
- cc65/include
- export CC65_LIB=/usr/local/lib/
- cc65/lib
- alias edit='xed -xc'
-
- Press Cmd+W & confirm the dialog to
- save the file. Finally, enter this
- command in the terminal window to run
- our script:
-
- . init.sh
-
- That's a dot & a space before the
- init.sh. This command will need to be
- run in any new terminal window when
- you want to use cc65.
-
- Creating your first program
- Because C is a compiled language, the
- program code is entered into plain
- text files. These files should have a
- '.c' extension. The cc65 compiler is
- then used to translate the source code
- file into an executable program.
-
- To keep things as simple as possible
- we will use the standard tools
- provided by the operating system. On
- Windows we will use Notepad for
- entering the source code. On OS X we
- will be using the Xcode editor which
- you have already seen. If you are
- using Linux replace 'notepad' or
- 'edit' in the instructions below with
- your favourite text file editor.
- Windows users enter this command:
-
- notepad first.c
-
- Notepad will ask if you want to create
- a new file, answer yes. OS X users
- enter this command:
-
- edit first.c
-
- Now type in (or copy & paste) the
- program below. To get the # on a Mac
- with a UK keyboard press alt/option &
- 3.
-
- // My first C program
-
- #include <stdio.h>
-
- void main(void)
-
- +
- puts("It works!");
- !
-
- Press Ctrl+S on Windows or Cmd+S on OS
- X to save the file. Now flip back to
- the command prompt/terminal window.
- Windows users enter the command:
-
- dir
-
- OS X or Linux users enter the command:
-
- ls -l
-
- The directory should show our
- 'first.c' file. Now we need to compile
- this into a C64 program. To do this,
- enter the command:
-
- cl65 first.c
-
- If all goes well, the command prompt
- should return with no other output
- (cc65 follows the Unix philosophy of
- 'no news is good news'). If you get an
- error message, swap back to the editor
- window, make any necessary corrections
- save the file, then enter the cl65
- command again at the command prompt.
-
- Once your program has compiled without
- errors, enter the 'dir' (or 'ls')
- command again and you should see a
- couple of new files, 'first.o' and
- 'first'. The 'first.o' file is an
- intermediary file created during the
- compilation. The file called 'first'
- is our C64 program.
-
- Next, load up x64, the VICE C64
- emulator. Select the option called
- 'Autostart' or 'Smart attach' in the
- 'File' menu. On Windows navigate to
- the c:\cc65\tut directory & select
- 'All files (*.*)' as the file type
- filter. OS X users navigate to the
- Documents/cc65 directory. Now double
- click on the file called 'first' &
- our program should load & run,
- displaying 'It works!' on the screen.
-
- That is, in a nutshell, the process
- for creating programs in C. This
- 'edit, compile, run' sequence of
- actions will soon become 2nd nature.
-
- Okay, let's take a look at the program
- code in more detail. The first thing
- to notice is that the code is written
- predominantly in lower case. C is case
- sensitive & all of its built-in
- keywords must be entered in lower
- case. The first line in the program is
- a comment line. The double slash
- characters mark the start of a comment
- & all text after the // up to the end
- of the line is ignored. C also
- supports comments that span multiple
- lines. All text between /* and */
- markers will be ignored.
-
- Skip past the #include line for now,
- we will come back to this in a moment.
-
- C programs are broken down into
- separate named blocks of code called
- 'functions'. Each function can take
- any number of parameters & can
- optionally return a single value. The
- next line in the program creates a
- function called 'main'. The word
- 'void' before the function name
- declares the type of the return value,
- in this case, void because we are not
- going to return a value from the
- function. The parameters of a function
- are listed after its name inside
- brackets. Again, 'void' here means the
- function takes no parameters.
-
- Typically, many programs follow the
- convention of using lower case for
- function names, often with multiple
- words separated by underscores. For
- example, 'move', 'fire' or
- 'show_high_scores'. Sometimes you
- may see programs or libraries that use
- mixed case function names such as
- 'NewList' & 'AddListitem'. These are
- not enforced by the compiler, they are
- just conventions used to make names
- consistent & readable.
-
- The function called 'main' serves a
- special purpose in C. It is auto-
- matically called when the program is
- run & therefore marks the starting
- point of the program. When all the
- instructions in the main function have
- completed, the program will exit &
- return back to BASIC. Every C program
- must have a 'main' function.
-
- The body of a function is contained
- within curly braces. This is the way C
- groups together lines of code into
- discrete blocks. Our 'main' function
- only contains one instruction that
- calls another function named 'puts'.
- The brackets contain the arguments
- passed to that function, in this
- example the string "It works!"
- delimited by double quotes. The 'puts'
- function is one of many standard
- functions defined by the C language &
- is used to print out a string. Notice
- that the instruction is followed by a
- semi-colon. This must be used to mark
- the end of every separate instruction
- in C.
-
- Before a function can be called, C
- needs to have been previously told
- about its name, what parameters it
- takes & what type of value it returns.
- The C compiler uses this info to check
- that the arguments you pass to the
- function match up with the parameters
- it expects. C is quite strict in this
- regard. For example, it would not
- allow you to pass a number to the
- 'puts' function which expects a string
- So, how does the compiler already know
- about 'puts' in our example program?
-
- The answer lies with the #include line
- at the start of the program. This
- instruction reads in another file
- containing declarations of functions
- that are in the standard library, one
- of which is 'puts'. These files are
- called 'header' files & have the
- extension '.h'. The one used here is
- 'stdio.h', short for 'standard input
- and output'. It contains functions
- used to read & write data to files &
- other devices including the screen.
-
- The core C language itself is very
- simple, consisting only of a few
- keywords for declaring functions &
- variables, testing conditions, looping
- & arithmetic operations. The rest of
- the features are provided by libraries
- of functions. The standard C language
- provides a good number of library
- functions for many purposes including
- string, file & memory handling. The
- cc65 compiler provides some additional
- libraries & you can also create your
- own libraries of often-used functions.
-
- Variables
- Now let's try using variables in C.
- Close the 'first.c' file & create a
- new file called 'var.c' at the command
- prompt:
-
- notepad var.c
-
- Enter the following program into this
- file:
-
- #include <stdio.h>
-
- void main(void)
-
- +
- int n = 1000;
- char c = 'X';
- char s[] = "Commodore";
- int a[5] = 1, 10, 100, 1000, 10000;!
- int i;
-
- printf("n = %d\n", n);
- printf("c = %c\n", c);
- printf("s = %s\n", s);
- printf("a =\n");
-
- for (i = 0; i < 5; ++i)
- +
- printf("%5d\n", a[i]);
- !
- !
-
- Save the file & compile it at the
- command prompt using the cl65 command
- as
- before:
-
- cl65 var.c
-
- When the program has compiled
- correctly, switch back to VICE. You
- could run the program using the same
- auto-load method as before but,
- because VICE has now set up device 8
- to point to our tutorial directory
- during the last auto-load, you can
- also enter the familiar load command
- directly into the C64 emulation:
-
- LOAD "VAR",8
- RUN
-
- The program should display the values
- of the variables. 'n' is a number
- variable, 'c' is a character, 's' is a
- string & 'a' is an array of numbers.
- These short variable names have been
- chosen so the code fits in the
- narrow columns of the magazine.
- Normally, variables would have longer,
- more descriptive names!
-
- Variables declared inside a function
- must be positioned at the start of the
- code block, that is, after the opening
- curly brace before any other inst-
- ructions. These variables will be
- 'local' to the function. In other
- words, they are only accessible by
- that function & only exist temporarily
- while the function is running. You may
- also create global variables in C by
- declaring them outside of any
- function. We will see an example of
- global variables later.
-
- Variable declarations follow this
- general format:
-
- type name = value;
-
- All variables in C must be declared to
- be a specific type. The type dictates
- what kind of data can be stored, the
- limit on its values & how much memory
- the variable takes up. The most
- commonly used types in cc65 are:
-
- char - characters or whole numbers
- from -128 to 127
- int - whole numbers from -32768 to
- 32767
- long - whole numbers up to +/-
- 2,147,483,647
-
- These are 'signed' types because they
- allow both positive & negative
- numbers. C also supports 'unsigned'
- types that allow larger positive-only
- values:
-
- unsigned char - numbers from 0 to
- 255
- unsigned int - numbers from 0 to
- 65535
- unsigned long - numbers up to
- 4,294,967,295
-
- The variable name can be any comb-
- ination of letters, numbers & under-
- scores (although it can't start with a
- number). Conventionally, variables
- have lower case names, often with
- words separated by underscores. For
- example, 'level', 'score',
- 'high_score' etc.
-
- A variable doesn't have to be assigned
- an initial value. Any variable without
- an explicit value will contain random
- garbage. To avoid errors in your
- programs it's usually a good idea to
- give variables an explicit initial
- value.
-
- Arrays
- C has no built-in type for strings,
- although it does allow a literal
- string to be created by putting it in
- double quotes. In C, a string is
- simply considered to be an array of
- characters.
-
- Arrays are declared by putting the
- size of the array in square brackets
- after the variable name. In the
- example program, the variable 's' is
- declared with empty brackets so the
- array will be as long as it needs to
- be to fit the string.
-
- The variable 'a' is declared as length
- 5 & has 5 values assigned to it.
- Notice the use of curly braces again
- for grouping these values together.
-
- To access an element in an array, the
- index number of that element is put in
- square brackets after the variable
- name. Index numbers always start at
- zero & go up to the array length -1.
- In the example program, we could
- access the first element of the
- array with a[0] & the last element
- with a[4]. Often, we would use some
- kind of loop to iterate through all
- the elements in an array & use a
- variable as the index.
-
- CONTINUED IN PART 1.2
-
-